package com.ts.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ts.office.SysExcel;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xhc on 2017/6/24.
 */
@Controller
public class SysController {
	@RequestMapping(value = "/exportOne",method = RequestMethod.POST)
	public String exportExcel(HttpServletRequest request, HttpServletResponse response){
		ServletOutputStream outputStream=null;
		try {
			String fileData = request.getParameter("fileData");
			//获取导出参数
			JSONObject param = JSONObject.parseObject(fileData);
			//文件名称
			String sTtile=param.getString("title");
			//多表头信息
			JSONArray headArr=param.getJSONArray("headData");
			//副标题信息
			JSONArray subTitleArr=param.getJSONArray("subTitles");
			//表格列信息、表格合计行
			JSONArray columnArr=param.getJSONArray("columns");
			//表格数据
			JSONArray rowsArr=param.getJSONArray("rows");
			//表格尾部信息
			JSONArray footerArr=param.getJSONArray("footer");
			//生成excel
			response.reset();
			response.setContentType("application/force-download");
			response.setHeader("Content-Disposition", "attachment;filename="+ new String((sTtile + ".xlsx").getBytes(), "iso-8859-1"));

			XSSFWorkbook workbook=SysExcel.exportXLSX(sTtile,headArr,subTitleArr,columnArr,rowsArr,footerArr);
			outputStream=response.getOutputStream();
			workbook.write(outputStream);
			outputStream.flush();
			outputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(outputStream!=null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}


}
